<template>
  <div class="user-trades">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>交易记录</h2>
      <p>查看您的所有银行卡交易记录</p>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form
        ref="searchFormRef"
        :model="searchForm"
        :inline="true"
        label-width="80px"
        class="search-form"
      >
        <el-form-item label="银行卡号">
          <el-select
            v-model="searchForm.cardId"
            placeholder="请选择银行卡"
            clearable
            style="width: 200px"
          >
            <el-option label="全部银行卡" value="" />
            <el-option
              v-for="card in cardList"
              :key="card.cardid"
              :label="formatCardNumber(card.cardid)"
              :value="card.cardid"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="交易类型">
          <el-select
            v-model="searchForm.tradeType"
            placeholder="请选择交易类型"
            clearable
            style="width: 120px"
          >
            <el-option label="全部类型" value="" />
            <el-option label="存款" value="存款" />
            <el-option label="取款" value="取款" />
            <el-option label="转账" value="转账" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="金额范围">
          <el-input
            v-model.number="searchForm.minAmount"
            placeholder="最小金额"
            type="number"
            style="width: 100px"
          />
          <span style="margin: 0 8px">-</span>
          <el-input
            v-model.number="searchForm.maxAmount"
            placeholder="最大金额"
            type="number"
            style="width: 100px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card income">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">总收入</div>
              <div class="stat-value">¥{{ stats.totalIncome.toLocaleString() }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card expense">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">总支出</div>
              <div class="stat-value">¥{{ stats.totalExpense.toLocaleString() }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card balance">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">净收支</div>
              <div class="stat-value" :class="{ negative: stats.netAmount < 0 }">
                ¥{{ stats.netAmount.toLocaleString() }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card count">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><DataLine /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">交易笔数</div>
              <div class="stat-value">{{ stats.totalCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 交易列表 -->
    <el-card class="trades-card">
      <template #header>
        <div class="card-header">
          <span>交易明细</span>
          <div class="header-actions">
            <el-button type="success" size="small" @click="exportTrades" :loading="exportLoading" :disabled="loading || tradeList.length === 0">
              <el-icon><Download /></el-icon>
              导出CSV ({{ tradeList.length }})
            </el-button>
            <el-radio-group v-model="viewMode" size="small">
              <el-radio-button label="list">列表视图</el-radio-button>
              <el-radio-button label="timeline">时间轴</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>

      <!-- 列表视图 -->
      <div v-if="viewMode === 'list'">
        <el-table
          :data="tradeList"
          v-loading="loading"
          stripe
          :default-sort="{ prop: 'tradedate', order: 'descending' }"
        >
          <el-table-column prop="tradedate" label="交易时间" width="160" sortable>
            <template #default="{ row }">
              {{ formatDateTime(row.tradedate) }}
            </template>
          </el-table-column>

          <el-table-column prop="tradetype" label="交易类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getTradeTypeColor(row.tradetype)" size="small">
                {{ row.tradetype }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="cardid" label="银行卡号" width="180">
            <template #default="{ row }">
              {{ formatCardNumber(row.cardid) }}
            </template>
          </el-table-column>

          <el-table-column prop="trademoney" label="交易金额" width="150" sortable>
            <template #default="{ row }">
              <span :class="getAmountClass(row.tradetype, row.trademoney)">
                {{ getAmountDisplay(row.tradetype, row.trademoney) }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="balance" label="余额" width="150">
            <template #default="{ row }">
              ¥{{ Number(row.balance || 0).toLocaleString() }}
            </template>
          </el-table-column>

          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.remark || '-' }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="text" @click="viewTradeDetail(row)">
                详情
              </el-button>
              <el-button size="small" type="text" @click="downloadReceipt(row)">
                回单
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 时间轴视图 -->
      <div v-if="viewMode === 'timeline'" class="timeline-view">
        <el-timeline>
          <el-timeline-item
            v-for="trade in tradeList"
            :key="trade.tradeid"
            :timestamp="formatDateTime(trade.tradedate)"
            placement="top"
          >
            <el-card class="timeline-card" @click="viewTradeDetail(trade)">
              <div class="timeline-content">
                <div class="trade-header">
                  <el-tag :type="getTradeTypeColor(trade.tradetype)" size="small">
                    {{ trade.tradetype }}
                  </el-tag>
                  <span :class="getAmountClass(trade.tradetype, trade.trademoney)" class="trade-amount">
                    {{ getAmountDisplay(trade.tradetype, trade.trademoney) }}
                  </span>
                </div>
                <div class="trade-info">
                  <div class="trade-card">银行卡：{{ formatCardNumber(trade.cardid) }}</div>
                  <div class="trade-balance">余额：¥{{ Number(trade.balance || 0).toLocaleString() }}</div>
                </div>
                <div v-if="trade.remark" class="trade-remark">
                  备注：{{ trade.remark }}
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>

        <!-- 时间轴分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[5, 10, 20]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && tradeList.length === 0" class="empty-state">
        <el-empty description="暂无交易记录">
          <el-button type="primary" @click="$router.push('/user/cards')">
            去银行卡页面
          </el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 交易详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="交易详情"
      width="500px"
    >
      <div v-if="selectedTrade" class="trade-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="交易流水号">
            {{ selectedTrade.tradeid }}
          </el-descriptions-item>
          <el-descriptions-item label="交易时间">
            {{ formatDateTime(selectedTrade.tradedate) }}
          </el-descriptions-item>
          <el-descriptions-item label="交易类型">
            <el-tag :type="getTradeTypeColor(selectedTrade.tradetype)">
              {{ selectedTrade.tradetype }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="银行卡号">
            {{ formatCardNumber(selectedTrade.cardid) }}
          </el-descriptions-item>
          <el-descriptions-item label="交易金额">
            <span :class="getAmountClass(selectedTrade.tradetype, selectedTrade.trademoney)" class="amount-large">
              {{ getAmountDisplay(selectedTrade.tradetype, selectedTrade.trademoney) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="交易后余额">
            ¥{{ Number(selectedTrade.balance || 0).toLocaleString() }}
          </el-descriptions-item>
          <el-descriptions-item label="备注信息" v-if="selectedTrade.remark">
            {{ selectedTrade.remark }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="downloadReceipt(selectedTrade)">
            下载回单
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Search,
  Refresh,
  Download,
  TrendCharts,
  Wallet,
  DataLine,
  Setting
} from '@element-plus/icons-vue'
import { userApi } from '@/api/user'

export default {
  name: 'UserTrades',
  components: {
    Search,
    Refresh,
    Download,
    TrendCharts,
    Wallet,
    DataLine,
    Setting
  },
  setup() {
    const route = useRoute()

    // 数据
    const cardList = ref([])
    const tradeList = ref([])
    const loading = ref(false)
    const exportLoading = ref(false)
    const viewMode = ref('list')

    // 搜索表单
    const searchFormRef = ref()
    const searchForm = reactive({
      cardId: '',
      tradeType: '',
      dateRange: [],
      minAmount: null,
      maxAmount: null
    })

    // 分页
    const pagination = reactive({
      page: 1,
      pageSize: 20,
      total: 0
    })

    // 对话框
    const detailDialogVisible = ref(false)
    const selectedTrade = ref(null)

    // 统计数据
    const stats = computed(() => {
      const income = tradeList.value
        .filter(trade => trade.tradetype === '存款' || (trade.tradetype === '转账' && trade.trademoney > 0))
        .reduce((sum, trade) => sum + Number(trade.trademoney), 0)

      const expense = tradeList.value
        .filter(trade => trade.tradetype === '取款' || (trade.tradetype === '转账' && trade.trademoney < 0))
        .reduce((sum, trade) => sum + Math.abs(Number(trade.trademoney)), 0)

      return {
        totalIncome: income,
        totalExpense: expense,
        netAmount: income - expense,
        totalCount: tradeList.value.length
      }
    })

    // 获取银行卡列表
    const fetchUserCards = async () => {
      try {
        const response = await userApi.getUserCards()
        if (response.code === 0) {
          cardList.value = response.data || []
        }
      } catch (error) {
        console.error('获取银行卡失败:', error)
      }
    }

    // 查询交易记录
    const loadTrades = async () => {
      try {
        loading.value = true
        
        // 构建查询参数 - 按照bank-front项目的格式
        const queryData = {
          tradeid: 0,
          cardid: searchForm.cardId || '',
          tradetype: searchForm.tradeType || '',
          minMoney: searchForm.minAmount || 0,
          maxMoney: searchForm.maxAmount || 0,
          remark: '',
          page: pagination.page,
          pageSize: pagination.pageSize
        }

        // 处理日期范围
        let begin, end
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          begin = searchForm.dateRange[0]
          end = searchForm.dateRange[1]
        }

        console.log('交易查询参数:', queryData, begin, end)
        
        const response = await userApi.pageTradeUser(queryData, begin, end)
        
        if (response && response.code === 0) {
          tradeList.value = response.data?.records || []
          pagination.total = response.data?.total || 0
        } else {
          console.error('查询交易记录失败:', response)
          ElMessage.error(response?.message || '查询交易记录失败')
          tradeList.value = []
          pagination.total = 0
        }
        
      } catch (error) {
        console.error('查询交易记录异常:', error)
        ElMessage.error('查询交易记录失败: ' + error.message)
        tradeList.value = []
        pagination.total = 0
      } finally {
        loading.value = false
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.page = 1
      loadTrades()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        cardId: '',
        tradeType: '',
        dateRange: [],
        minAmount: null,
        maxAmount: null
      })
      pagination.page = 1
      loadTrades()
    }

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      pagination.page = 1
      loadTrades()
    }

    const handleCurrentChange = (page) => {
      pagination.page = page
      loadTrades()
    }

    // 查看交易详情
    const viewTradeDetail = (trade) => {
      selectedTrade.value = trade
      detailDialogVisible.value = true
    }

    // 导出交易记录
    const exportTrades = async () => {
      try {
        exportLoading.value = true
        
        if (tradeList.value.length === 0) {
          ElMessage.warning('没有数据可导出')
          return
        }

        // 获取所有数据用于导出
        const exportParams = {
          tradeid: 0,
          cardid: searchForm.cardId || '',
          tradetype: searchForm.tradeType || '',
          minMoney: searchForm.minAmount || 0,
          maxMoney: searchForm.maxAmount || 0,
          remark: '',
          page: 1,
          pageSize: pagination.total || 10000 // 导出所有数据
        }

        // 处理日期范围
        let begin, end
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          begin = searchForm.dateRange[0]
          end = searchForm.dateRange[1]
        }

        const response = await userApi.pageTradeUser(exportParams, begin, end)
        
        if (response && response.code === 0) {
          const exportData = response.data?.records || []
          
          if (exportData.length === 0) {
            ElMessage.warning('没有数据可导出')
            return
          }

          // 使用CSV导出工具 - 使用用户端专用的导出配置
          const { CSVExporter, userTradeExportColumns } = await import('@/utils/csvExport')
          CSVExporter.exportToCSV(exportData, userTradeExportColumns, '我的交易记录')
          
          ElMessage.success(`成功导出 ${exportData.length} 条交易记录`)
        } else {
          ElMessage.error(response?.message || '获取导出数据失败')
        }
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      } finally {
        exportLoading.value = false
      }
    }

    // 下载回单
    const downloadReceipt = (trade) => {
      ElMessage.info('回单下载功能开发中')
    }

    // 工具函数
    const formatCardNumber = (cardNumber) => {
      if (!cardNumber) return ''
      return cardNumber.replace(/(\d{4})(?=\d)/g, '$1 ')
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      return new Date(dateTime).toLocaleString()
    }

    const getTradeTypeColor = (type) => {
      const colorMap = {
        '存款': 'success',
        '取款': 'warning',
        '转账': 'info'
      }
      return colorMap[type] || 'info'
    }

    const getAmountClass = (type, amount) => {
      if (type === '存款' || (type === '转账' && amount > 0)) {
        return 'amount-positive'
      } else if (type === '取款' || (type === '转账' && amount < 0)) {
        return 'amount-negative'
      }
      return ''
    }

    const getAmountDisplay = (type, amount) => {
      const absAmount = Math.abs(Number(amount))
      if (type === '存款' || (type === '转账' && amount > 0)) {
        return `+¥${absAmount.toLocaleString()}`
      } else if (type === '取款' || (type === '转账' && amount < 0)) {
        return `-¥${absAmount.toLocaleString()}`
      }
      return `¥${absAmount.toLocaleString()}`
    }

    // 初始化
    onMounted(() => {
      fetchUserCards()
      loadTrades()
    })

    return {
      cardList,
      tradeList,
      loading,
      exportLoading,
      viewMode,
      searchFormRef,
      searchForm,
      pagination,
      detailDialogVisible,
      selectedTrade,
      stats,
      fetchUserCards,
      loadTrades,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      viewTradeDetail,
      exportTrades,
      downloadReceipt,
      formatCardNumber,
      formatDateTime,
      getTradeTypeColor,
      getAmountClass,
      getAmountDisplay
    }
  }
}
</script>

<style lang="scss" scoped>
.user-trades {
  .page-header {
    margin-bottom: 24px;
    
    h2 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 24px;
    }
    
    p {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .search-card {
    margin-bottom: 20px;

    .search-form {
      .el-form-item {
        margin-bottom: 16px;
      }
    }
  }

  .stats-row {
    margin-bottom: 20px;

    .stat-card {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      &.income {
        border-left: 4px solid #67c23a;
      }

      &.expense {
        border-left: 4px solid #f56c6c;
      }

      &.balance {
        border-left: 4px solid #409eff;
      }

      &.count {
        border-left: 4px solid #e6a23c;
      }

      .stat-content {
        display: flex;
        align-items: center;
        padding: 20px;

        .stat-icon {
          font-size: 32px;
          margin-right: 16px;
          opacity: 0.8;
        }

        .stat-info {
          .stat-title {
            font-size: 14px;
            color: #909399;
            margin-bottom: 8px;
          }

          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;

            &.negative {
              color: #f56c6c;
            }
          }
        }
      }
    }
  }

  .trades-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .timeline-view {
      .timeline-card {
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .timeline-content {
          .trade-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;

            .trade-amount {
              font-size: 16px;
              font-weight: bold;
            }
          }

          .trade-info {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            color: #606266;
            margin-bottom: 8px;
          }

          .trade-remark {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }

    .pagination-wrapper {
      margin-top: 20px;
      text-align: center;
    }

    .empty-state {
      text-align: center;
      padding: 60px 0;
    }
  }

  .trade-detail {
    .amount-large {
      font-size: 18px;
      font-weight: bold;
    }
  }

  .dialog-footer {
    text-align: right;
  }

  // 金额样式
  .amount-positive {
    color: #67c23a;
  }

  .amount-negative {
    color: #f56c6c;
  }
}

@media (max-width: 768px) {
  .user-trades {
    .search-form {
      .el-form-item {
        margin-right: 0;
        margin-bottom: 12px;
      }
    }

    .stats-row {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }
}
</style> 